package com.fellansoft.moviescollection.activities;

import android.app.Activity;
import android.content.*;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.fellansoft.moviescollection.R;
import com.fellansoft.moviescollection.business.BusinessConstants;
import com.fellansoft.moviescollection.business.DataManager;
import com.fellansoft.moviescollection.data.Movie;
import com.fellansoft.moviescollection.utils.ActivityUtils;
import com.fellansoft.moviescollection.utils.ApplicationVariables;

import java.text.DateFormat;
import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: Pufi
 * Date: 12.05.2012
 * Time: 17:43
 * To change this template use File | Settings | File Templates.
 */
@SuppressWarnings({"deprecation"})
public class ViewMovie extends Activity{

    /*
     * The application context used to register receivers
     */
    private Context context;
    /*
     * The movie wanted to view
     */
    static public Movie m;
    /*
     * Text vie for the title of the movie
     */
    private TextView titleTextView;
    /*
     * TextView for the categories of the movie
     */
    private TextView categoriesTextView;
    /*
     * TextView for the description of the movie
     */
    private TextView descriptionTextView;
    /*
     * TextView for the realease Date of the movie
     */
    private TextView releaseDateTextView;
    /*
     * Raiting Bar to view the raiting of the movie
     */
    private RatingBar ratingBar;
    /*
     * Text view for the release date
     */
    private TextView releaseDate;
    /*
     * Sequence of chars for the categries
     */
    private CharSequence[] categories;
    /*
     * View if the category is selected or not
     */
    private boolean[] categoriesSelection;
    /*
     * Button for editing a movie
     */
    private Button editMovie;
    /*
     * CheckBox to see if a movie is or not in the watchlist
     */
    private CheckBox watchlistCheckbox;
    /*
     * CeckBox to see if a movie is or not in the favorites list
     */
    private CheckBox favouriteCheckbox;
    /*
     * Button for deleting a movie
     */
    private Button deleteButton;
    /*
     * Image view for the Movies profile picture
     */
    private ImageView imageView;
    /*
     * Value for the date picker
     */
    public final int EDIT_MOVIE = 11924;

    /**
     * Intent filter for the intents sent when the book was saved successfully
     */
    private static IntentFilter deleteMovieSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the book was not saved successfully
     */
    private static IntentFilter deleteMovieErrorIntentFilter;

    /**
     * Receiver for the intents sent when the book was saved successfully to database
     */
    private static BroadcastReceiver deleteMovieSuccessReceiver;

    /**
     * Receiver for the intents sent when there was a problem saving the new book to database
     */
    private static BroadcastReceiver deleteMovieErrorReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTheme(android.R.style.Theme_Holo);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Set the content view
        setContentView(R.layout.viewmovie);

        context = ApplicationVariables.getApplicationContext();

        deleteButton=(Button)findViewById(R.id.deleteMovie);
        titleTextView = (TextView)findViewById(R.id.text_title_field);
        releaseDateTextView = (TextView) findViewById(R.id.viewReleaseDate);
        descriptionTextView=(TextView)findViewById(R.id.viewDescription);
        imageView=(ImageView)findViewById(R.id.viewImage);
        editMovie=(Button)findViewById(R.id.editMovie);
        categoriesTextView =(TextView)findViewById(R.id.viewCategories);
        ratingBar =(RatingBar) findViewById(R.id.rating);
        watchlistCheckbox=(CheckBox)findViewById(R.id.watchCheckBV);
        favouriteCheckbox=(CheckBox)findViewById(R.id.favoriteCheckBV);

        setUpListeners();

        setFields();
    }

    private void setFields()
    {
        String categ= "";
        m=DataManager.getInstance().getMovie();
        titleTextView.setText(m.getTitle());
        releaseDateTextView.setText(DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(m.getReleaseDate()));
        descriptionTextView.setText(m.getDescription());
        imageView.setImageURI(m.getCoverPhoto());

        categories = ApplicationVariables.getApplicationContext().getResources().getStringArray(R.array.Categories);
        categoriesSelection = new boolean[categories.length ];
        categoriesSelection=m.getCategories();
        for(int i=0;i<categoriesSelection.length;i++)
        {
            if(categoriesSelection[i]==true)
                if(categ.length()>0)
                    categ+=", "+categories[i];
                else
                    categ+=categories[i];
        }
        categoriesTextView.setText(categ);

        ratingBar.setRating(m.getOwnRating());
        watchlistCheckbox.setChecked(m.getWatchList());
        favouriteCheckbox.setChecked(m.getFavorite());
    }

    private void setUpListeners()
    {
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (deleteMovieSuccessIntentFilter == null)
                    deleteMovieSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_MOVIES_DELETED_SUCCESSFULLY);
                if (deleteMovieSuccessReceiver == null)
                    deleteMovieSuccessReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context localContext, Intent intent) {
                            try {
                                context.unregisterReceiver(deleteMovieSuccessReceiver);
                            } catch(IllegalArgumentException e) {
                                e.printStackTrace();
                            }

                            //Hide the spinning dialog
                            ActivityUtils.hideProgressDialog(ViewMovie.this);

                            //Show a message on the screen

                            ViewMovie.this.setResult(RESULT_OK);
                            finish();
                        }
                    };
                context.registerReceiver(deleteMovieSuccessReceiver, deleteMovieSuccessIntentFilter);

                if (deleteMovieErrorIntentFilter == null)
                    deleteMovieErrorIntentFilter = new IntentFilter(BusinessConstants.BC_MOVIE_SAVED_ERROR);
                if (deleteMovieErrorReceiver == null)
                    deleteMovieErrorReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context localContext, Intent intent) {
                            try {
                                context.unregisterReceiver(deleteMovieErrorReceiver);
                            } catch(IllegalArgumentException e) {
                                e.printStackTrace();
                            }

                            //Hide the spinning dialog
                            ActivityUtils.hideProgressDialog(ViewMovie.this);

                            //Show a message on the screen
                           // Toast.makeText(ViewMovie.this,ViewMovie.this.getResources().getString(R.string.delete_error_message),Toast.LENGTH_SHORT).show();
                        }
                    };
                context.registerReceiver(deleteMovieErrorReceiver,deleteMovieErrorIntentFilter);

                ActivityUtils.showProgressDialog(ViewMovie.this);

                DataManager.getInstance().requestDeleteMovie(m.getId());

            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ViewMovie.this, ViewPictures.class);
                startActivity(intent);
            }
        });
        editMovie.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(ViewMovie.this, EditMovie.class);
                startActivityForResult(intent,EDIT_MOVIE);
            }
        });
    }

    public void onPause()
    {
        super.onPause();
        if (deleteMovieSuccessReceiver != null)
        {
            try{
                this.unregisterReceiver(deleteMovieSuccessReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            deleteMovieSuccessReceiver = null;
        }
    }

     protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {
            case EDIT_MOVIE:
                if (resultCode == RESULT_OK) {
                    setFields();
                    ViewMovie.this.setResult(RESULT_OK);
                }
                break;
        }
    }
}